package com.hanhai.zrb.backend.util;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hanhai.zrb.backend.admin.model.Privilege;

public class MenuUtil {

	protected final static Logger logger = LoggerFactory
			.getLogger(MenuUtil.class);

	// 已经按照level排序
	public static List<Privilege> buildList(List<Privilege> privilegeList) {
		List<Privilege> rootList = new ArrayList<Privilege>();
		Map<Integer, Privilege> rootMap = new HashMap<Integer, Privilege>();

		for (Privilege privilege : privilegeList) {
			Integer acl = privilege.getAcl();
			Integer pacl = privilege.getPacl();
			rootMap.put(acl, privilege);
			if (pacl == null) {
				logger.error("pacl is null");
				continue;
			}
			if (pacl.equals(-1)) {
				rootList.add(privilege);
			} else {
				Privilege fatherNode = rootMap.get(pacl);
				addChild(fatherNode, privilege);
			}
		}
		return rootList;
	}

	static Map<String, Object> createNode(Integer id, String text, String url) {
		Map<String, Object> node = new HashMap<String, Object>();
		node.put("id", id);
		node.put("text", text);
		if (url != null && !"".equals(url)) {
			node.put("href", url);
		}

		return node;
	}

	public static void addChild(Privilege father, Privilege child) {
		if (father == null) {
			logger.error("Father is null");
			return;
		}
		List<Privilege> fatherChildList = father.getChildren();
		List<Privilege> childList;
		if (fatherChildList == null) {
			childList = new ArrayList<Privilege>();
			father.setChildren(childList);
		} else {
			childList = fatherChildList;
		}
		childList.add(child);
		return;
	}

	public static void putName2Text(JSONObject jsono){
		jsono.put("text", jsono.getString("name"));
		JSONArray array = jsono.getJSONArray("children");
		if(array == null ||array.size()==0){
			return;
		}
		for(int i=0;i<array.size();i++){			
			putName2Text(array.getJSONObject(i));
		}
	}
	
}
